// stores/cart.ts
import { defineStore } from 'pinia'
import {clearCarts, deleteCarts} from "../api/details.ts";
import { Modal } from 'ant-design-vue';
import { Session } from '../utils/storage.ts';

type CartItem = {
  id: string | number
  name: string
  price: number
  color?: string
  size: string
  qty: number,
  favorite: boolean,
}

export const useCartStore = defineStore('cart', {
  state: () => ({
    items: [] as CartItem[],
    goods :[],
    shopCartList: [] as any[],
    collectList: [] as any[],
  }),

  actions: {
    setShopCart(chartList: any) {
      this.shopCartList = chartList;
      Session.set('cartList', chartList)
    },

    getShopCart() {
      return Session.get('cartList') || null
    },

    setCollect(chartList: any) {
      this.shopCartList = chartList;
      Session.set('collectList', chartList)
    },

    getCollect() {
      return Session.get('collectList') || null
    },

    addItem(item: CartItem) {
      this.items.push(item)
    },
   
     //  移除单个商品通过索引删除
     async removeItemByIndex(index: number, id: number) {
      this.items.splice(index, 1)
       await deleteCarts({id}).then(()=>{
      })
      this.$persist?.()
    },
     
  },

  getters: {
    totalItems: (state) => state.items.reduce((sum, i) => sum + i.qty, 0),

    // 新增商品总价计算（含两位小数）
    totalPrice(): number {
      const rawTotal = this.items.reduce((acc, item) => {
        // 防御性计算：确保数值类型
        const price = Number(item.price) || 0
        const qty = Number(item.qty) || 1 // 数量默认为1
        return acc + (price * qty)
      }, 0)

      // 处理精度并保留两位小数
      return Number(rawTotal.toFixed(2))
    }

  },
  persist: {
    key: 'myapp_cart',
    storage: localStorage,
    paths: ['items']
  }
})
